const sys = require(`./system.js`)
const title = '助学查盲盒开盲盒'
const $ = sys.$(title)

sys.run($, 'task:all', (resList, cookie, index, username, password, item) => {
  return new Promise(async resolve => {
    // 请求接口
    // const box = await $.publicJS.isBoxList($, cookie)
    // const box = true
    // console.log(box);
    // 需要开盲盒
    // if (box) {
    //   let infoList = $.localStorage.get('task:all', 'localStorage') || []
    //   const infoList2 = infoList.filter(item => item['可用盲盒'] > 0)
    //   if (infoList2.length > 0) {
    //     // 取 1 个号
    //     const info = infoList2[0]
    //     const u = info.username
    //     const p = info.password
    //     const cookie = await $.publicJS.checkCookie($, $.localStorage.get(`${u}-cookie`, 'localStorage'), u, p)
    //     const bList = await $.publicJS.boxList($, cookie)
    //     const note = bList[bList.length - 1].note

    //     const boxResp = await $.publicJS.useBox($, cookie)
    //     console.log('boxResp=====', boxResp);

    //     // 盲盒减 1
    //     infoList.find(item => item.username == info.username)['可用盲盒'] -= 1
    //     $.localStorage.set('task:all', infoList, 'localStorage')

    //     // 追加信息
    //     resList.push({
    //       username: u,
    //       note: note,
    //       ...boxResp
    //     })
    //   }
    // }

    const ub = item['可用盲盒']
    console.log('可用盲盒检查', username, ub + '个盲盒');
    if(ub != 0) {
        const cookie = await $.publicJS.checkCookie($, $.localStorage.get(`${username}-cookie`, 'localStorage'), username, password)
        for (let i = 0; i < ub; i++) {
            const resp = await $.publicJS.useBox($, cookie)
            console.log('开启盲盒', username, resp.name);
        }
        item['可用盲盒'] = 0
        console.log('结束')
    }
    resList.push(item)
    resolve(resList)

  })
}, (resList) => {
  console.log('任务结束 resList:', resList)
  if (resList && resList.length > 0) {
    const resListStr = JSON.stringify(resList, null, 2)
    $.notify.sendNotify(title, resListStr)
  }
})
